package com.tevintao.marketingsystem.provider;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.text.TextUtils;

import com.tencent.mm.modelvoice.MediaRecorder;
import com.tevintao.marketingsystem.commen.UrlConfig;
import com.tevintao.marketingsystem.log.LogManager;
import com.tevintao.marketingsystem.services.AccountManager;
import com.tevintao.marketingsystem.services.TaskLogicService;
import com.tevintao.marketingsystem.task.ReportMessage;
import com.tevintao.marketingsystem.task.WxUiViewConfig;
import com.tevintao.marketingsystem.tool.DownloadFile;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;


public class ChatNewChatDB {

    @SuppressLint("SdCardPath")
    public static final String SQL_NAME = "/mnt/sdcard/ms/newchat.sqlite";//数据库名称。
    public static final String MAIN_DATA_TABLE_NAME = "newchat";//表名。
    public static final String FRIEND_TABLE_NAME = "friend";//好友列表
    public static final String TABLE_NAME_SEND_MESSAGE = "sendMsg";

    public static String createContactsDb = "create table if not exists " + MAIN_DATA_TABLE_NAME + "( "
            + "id INTEGER PRIMARY KEY, "
            + "account varchar(30), "
            + "talker varchar(50), "
            + "nickName varchar(50), "
            + "content varchar(50), "
            + "filePath varchar(50), "
            + "type INTEGER ); ";


    public static String createFriendDb = "create table if not exists " + FRIEND_TABLE_NAME + "( "
            + "username varchar(30) PRIMARY KEY, "
            + "account varchar(30), "
            + "updated BOOLEAN, "
            + "isMale varchar(10), " //是否是男性
            + "coverPath varchar(50) DEFAULT '', "
            + "updatedCover BOOLEAN DEFAULT 0 , "
            + "nickname varchar(50) ); ";

    //    String account, String talker, String nikeName, String imgPath, String content, long createTime, int type
    public static String sendMessageDb = "create table if not exists " + TABLE_NAME_SEND_MESSAGE + "( "
            + "id INTEGER PRIMARY KEY, "
            + "account varchar(30), "
            + "talker varchar(50), "
            + "nikeName varchar(50), "
            + "imgPath varchar(100) DEFAULT '', "
            + "content varchar(50), "
            + "createTime INTEGER, "
            + "type INTEGER, "
            + "failedTime INTEGER DEFAULT 0, "
            + "isSend BOOLEAN DEFAULT 0 ); ";

    private static ChatNewChatDB ourInstance = new ChatNewChatDB();

    public static ChatNewChatDB getInstance() {
        return ourInstance;
    }

    private SQLiteDatabase mDatabase;


    private ChatNewChatDB() {
    }

    public SQLiteDatabase getDb() {
        if (null == mDatabase) {
            File dbFile = new File(SQL_NAME);
            if (dbFile.exists()) {
                mDatabase = SQLiteDatabase.openOrCreateDatabase(dbFile, null);
            } else if (!dbFile.exists()) {
                try {
                    mDatabase = SQLiteDatabase.openOrCreateDatabase(dbFile, null);
                    LogManager.getInstance().logError("mDatabase = " + mDatabase);
                    mDatabase.execSQL(createContactsDb);
                    mDatabase.execSQL(createFriendDb);
                    mDatabase.execSQL(sendMessageDb);
                } catch (SQLException e) {
                    e.printStackTrace();
                    LogManager.getInstance().logError(" SQLException " + e);
                }
            }
        }
        return mDatabase;
    }

    public Cursor getAllMessage(String account) {
        return getDb().query(MAIN_DATA_TABLE_NAME, null, "account=? ", new String[]{account}, null, null, null);
    }

    public Cursor getAllFriend(String account) {
        return getDb().query(MAIN_DATA_TABLE_NAME, null, "account=?", new String[]{account}, null, null, null);
    }

    public Cursor getNoPathFriend(String account) {
        return getDb().query(FRIEND_TABLE_NAME, null, "account=? and coverPath='' ", new String[]{account}, null, null, null);
    }

    public int insertMessage(String jsonStr) {
        int count = 0;
        try {
            JSONArray jsonArray = new JSONArray(jsonStr);
            for (int i = 0, len = jsonArray.length(); i < len; i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                boolean insert = insertByJsonObj(jsonObject);
                if (insert) {
                    count++;
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return count;
    }

    private boolean insertByJsonObj(JSONObject jsonObject) {
        if (null == jsonObject) {
            return false;
        }

        try {
            String account = jsonObject.getString(ReportMessage.KEY_PARAMS_ACCOUNT);
            String talker = jsonObject.getString(ReportMessage.KEY_PARAMS_TALKER);
            String nikeName = jsonObject.getString(ReportMessage.KEY_PARAMS_NIKE_NAME);
            String content = jsonObject.getString(ReportMessage.KEY_PARAMS_CONTENT);
            String urlPath = jsonObject.getString(ReportMessage.KEY_FROM_FILE_PATH);
            int type = jsonObject.getInt(ReportMessage.KEY_PARAMS_TYPE);

            if (type == ReportMessage.MESSAGE_TYPE_PICTURE) {
                String fileName = urlPath.substring(urlPath.lastIndexOf("/") + 1);
                String savePath = new File(AccountManager.PICTURE_PATH, fileName).getAbsolutePath();
                boolean downloadSuccess = downLoadUrl(urlPath, savePath);
                if (!downloadSuccess) {
                    LogManager.getInstance().logInfo("下载图片出错");
                    return false;
                } else {
                    urlPath = savePath;
                }
            } else if (type == ReportMessage.MESSAGE_TYPE_VOICE) {
                String fileName = urlPath.substring(urlPath.lastIndexOf("/") + 1);
                String savePath = new File(AccountManager.PICTURE_PATH, fileName).getAbsolutePath();
                boolean downloadSuccess = downLoadUrl(urlPath, savePath);
                if (!downloadSuccess) {
                    LogManager.getInstance().logInfo("下载语音文件出错");
                    return false;
                } else {
                    urlPath = savePath;
                    LogManager.getInstance().logInfo("下载语音文件 savePath" + savePath);
                    String pcmName = fileName.replace(".silk", ".pcm");
                    String pcmPath = new File(AccountManager.PICTURE_PATH, pcmName).getAbsolutePath();
                    LogManager.getInstance().logInfo("pcmPath = " + pcmPath);
                    boolean decordState = MediaRecorder.getWxCoder(savePath, pcmPath);
                    LogManager.getInstance().logInfo("pcmPath = " + pcmPath + "  decordState = " + decordState);
                    if (decordState) {
                        urlPath = pcmPath;
                    }
                }
            }

            ContentValues contentValues = new ContentValues();
            contentValues.put(ReportMessage.KEY_PARAMS_ACCOUNT, account);
            contentValues.put(ReportMessage.KEY_PARAMS_TALKER, talker);
            contentValues.put(ReportMessage.KEY_PARAMS_NIKE_NAME, nikeName);
            contentValues.put(ReportMessage.KEY_PARAMS_CONTENT, content);
            contentValues.put(ReportMessage.KEY_FROM_FILE_PATH, urlPath);
            contentValues.put(ReportMessage.KEY_PARAMS_TYPE, type);
            return getDb().insert(MAIN_DATA_TABLE_NAME, null, contentValues) > 0;
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return false;
    }

    private boolean downLoadUrl(String urlPath, String savePath) {

        boolean exitMsPic = TaskLogicService.checkPic();
        if (!exitMsPic) {
            return false;
        }

        String url = UrlConfig.URL_BASE + "media/" + urlPath;
        LogManager.getInstance().logInfo(" url = " + url + " savePath = " + savePath);
        File picFile = new File(savePath);
        if (picFile.exists()) {
            LogManager.getInstance().logInfo("文件已经存在");
            return true;
        } else {
            boolean downSuccess = DownloadFile.downLoad(url, savePath);
            if (!downSuccess) {
                LogManager.getInstance().logError("下载文件错误");
                boolean deleteFailedFile = picFile.delete();
                if (!deleteFailedFile) {
                    LogManager.getInstance().logError("删除下载失败的文件错误");
                }
                return false;
            } else {
                return true;
            }
        }
    }

    private boolean deleteById(int id) {
        return getDb().delete(MAIN_DATA_TABLE_NAME, "id=?", new String[]{"" + id}) > 0;
    }


    public int delete(String selection, String[] selectionArgs) {
        return getDb().delete(MAIN_DATA_TABLE_NAME, selection, selectionArgs);
    }

    public static final String KEY_FRIEND_USER_NAME = "KEY_FRIEND_USER_NAME";
    public static final String KEY_FRIEND_NIKE_NAME = "KEY_FRIEND_NIKE_NAME";
    public static final String KEY_FRIEND_SEX = "KEY_FRIEND_SEX";

    public JSONArray inertFriend(String account, String friendJsonArray) {
        ArrayList<String> mUserNames = new ArrayList<>();

        Cursor cursor = getDb().query(FRIEND_TABLE_NAME, null, "account=?", new String[]{account}, null, null, null);
        if (null != cursor) {
            LogManager.getInstance().logInfo(account + " 好友数量  = " + cursor.getCount());
            while (cursor.moveToNext()) {
                String userName = cursor.getString(cursor.getColumnIndex("username"));
                mUserNames.add(userName);
            }
            cursor.close();
        }

        JSONArray newFriendJson = new JSONArray();
        int count = 0;
        try {
            JSONArray jsonArray = new JSONArray(friendJsonArray);
            for (int i = 0, len = jsonArray.length(); i < len; i++) {
                JSONObject jo = jsonArray.getJSONObject(i);

                String userName = jo.getString(KEY_FRIEND_USER_NAME);
                if (mUserNames.contains(userName)) {
                    LogManager.getInstance().logInfo(userName + "已经存在与数据库");
                    continue;
                }
                String nikeName = jo.getString(KEY_FRIEND_NIKE_NAME);
                ContentValues contentValues = new ContentValues();
                contentValues.put("username", userName);
                contentValues.put("nickname", nikeName);
                contentValues.put("account", account);
                contentValues.put("updated", false);
                long insertNum = getDb().insert(FRIEND_TABLE_NAME, null, contentValues);
                if (insertNum > 0) {
                    newFriendJson.put(jo);
                }
//                LogManager.getInstance().logInfo("insertNum = " + insertNum);
                count += insertNum;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        LogManager.getInstance().logError("新朋友 = " + newFriendJson.length());
        return newFriendJson;
    }

    public int deleteById(String wxId) {
        return getDb().delete(FRIEND_TABLE_NAME, "username=?", new String[]{wxId});
    }

    public int clearFriend() {
        return getDb().delete(FRIEND_TABLE_NAME, null, null);
    }

    public int updateFriendFinish(String jsonArray) {
        if (TextUtils.isEmpty(jsonArray)) {
            return -1;
        }
        int count = 0;
        try {
            JSONArray ja = new JSONArray(jsonArray);
            for (int i = 0, len = ja.length(); i < len; i++) {
                String userName = ja.getString(i);
                ContentValues contentValues = new ContentValues();
                contentValues.put("updated", true);
                int updateNum = getDb().update(FRIEND_TABLE_NAME, contentValues, "username=?", new String[]{userName});
//                LogManager.getInstance().logInfo("update state = userName = " + userName + " updateNum = " + updateNum);
                if (updateNum > 0) {
                    count++;
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return count;
    }

    public int updateChatFriendCover(ContentValues values, String selection, String[] selectionArgs) {
        return getDb().update(FRIEND_TABLE_NAME, values, selection, selectionArgs);
    }

    public void disAbleFriend() {
        Cursor cursor = getDb().query(FRIEND_TABLE_NAME, null, null, null, null, null, null);
        if (null == cursor) {
            return;
        }
        LogManager.getInstance().logInfo("好友数量" + cursor.getCount());
        ArrayList<String> mUserNames = new ArrayList<>();
        while (cursor.moveToNext()) {
            String userName = cursor.getString(cursor.getColumnIndex("username"));
            mUserNames.add(userName);
        }
        cursor.close();


        int count = 0;
        for (String userName : mUserNames) {
            ContentValues contentValues = new ContentValues();
            contentValues.put("updated", false);
            int updateNum = getDb().update(FRIEND_TABLE_NAME, contentValues, "username=?", new String[]{userName});
//            LogManager.getInstance().logInfo("update state = userName = " + userName + " updateNum = " + updateNum);
            if (updateNum > 0) {
                count++;
            }
        }

        LogManager.getInstance().logInfo("disAbleFriend count = " + count);
    }

    public JSONArray getNoReportFriendJsonArray() {
        Cursor cursor = getDb().query(FRIEND_TABLE_NAME, null, "updated=?", new String[]{"0"}, null, null, null);
        if (null == cursor) {
            return null;
        }
        JSONArray jsonArray = new JSONArray();
        while (cursor.moveToNext()) {
            JSONObject jsonObject = new JSONObject();
            String userName = cursor.getString(cursor.getColumnIndex("username"));
            String nikeName = cursor.getString(cursor.getColumnIndex("nickname"));
            String sex = cursor.getString(cursor.getColumnIndex("isMale"));
            try {
                jsonObject.put(KEY_FRIEND_USER_NAME, userName);
                jsonObject.put(KEY_FRIEND_NIKE_NAME, nikeName);
                jsonObject.put(KEY_FRIEND_SEX, sex);
                jsonArray.put(jsonObject);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        cursor.close();
        return jsonArray;
    }

    public Cursor getNoUpdateFriendIcon() {
        return getDb().query(FRIEND_TABLE_NAME, null, "updatedCover=? and updated<>0 ", new String[]{"0"}, null, null, null);
    }

    public boolean updateFriendIconSuccess(String wxId) {
        ContentValues contentValues = new ContentValues();
        contentValues.put("updatedCover", true);
        return getDb().update(FRIEND_TABLE_NAME, contentValues, "username=?", new String[]{wxId}) > 0;
    }


    public long changeFriendSex(String talker, String isMale) {
        ContentValues contentValues = new ContentValues();
        contentValues.put("isMale", isMale);
        contentValues.put("updated", false);
        return getDb().update(FRIEND_TABLE_NAME, contentValues, "username=?", new String[]{talker});
    }

    //            + "account varchar(30), "
//            + "talker varchar(50), "
//            + "nikeName varchar(50), "
//            + "imgPath varchar(100), "
//            + "content varchar(50), "
//            + "createTime INTEGER, "
//            + "type INTEGER, "
//            + "isSend BOOLEAN DEFAULT 0 ); ";
    public long insertSendMessage(String account, String talker, String nikeName, String imgPath, String content, long createTime, int type) {
        ContentValues contentValues = new ContentValues();
        contentValues.put("account", account);
        contentValues.put("talker", talker);
        contentValues.put("nikeName", nikeName);
        contentValues.put("imgPath", imgPath);
        contentValues.put("content", content);
        contentValues.put("createTime", createTime);
        contentValues.put("type", type);
        return getDb().insert(TABLE_NAME_SEND_MESSAGE, null, contentValues);
    }

    public Cursor getNeedReportMessage() {
        return getDb().query(TABLE_NAME_SEND_MESSAGE, null, "isSend=0 and failedTime<5 ", new String[]{}, null, null, null);
    }

    public long updateSuccess(String id) {
        ContentValues contentValues = new ContentValues();
        contentValues.put("isSend", true);
        return getDb().update(TABLE_NAME_SEND_MESSAGE, contentValues, "id=?", new String[]{id});
//        return getDb().delete(TABLE_NAME_SEND_MESSAGE, "id=?", new String[]{id});
    }

    public long updateFailedTimes(String id, int times) {
        ContentValues contentValues = new ContentValues();
        contentValues.put("failedTime", times);
        return getDb().update(TABLE_NAME_SEND_MESSAGE, contentValues, "id=?", new String[]{id});
    }

    public long uploadFailed(String id) {
        Cursor cursor = getDb().query(TABLE_NAME_SEND_MESSAGE, null, "id=?", new String[]{id}, null, null, null);
        if (cursor.moveToNext()) {
            int failed = cursor.getInt(cursor.getColumnIndex("failedTime"));
            LogManager.getInstance().logError("已上报失败次数 = " + failed);
            cursor.close();
            return updateFailedTimes(id, failed + 1);
        }
        return -1;
    }
}